﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Windows.Browser;
using VMWorkshop.Domain;

namespace VMWorkshop.Silverlight.Models
{
    public class WebClientPost
    {
        private WebClient _client;
        private Uri _serviceLocation;
        private string _method = "POST";
        private IList<IUrlSerializer> _data = null;

        public event EventHandler PostComplete;

        public WebClientPost(Uri serviceLocation)
        {
            this._client = new WebClient();
            this._client.Headers[HttpRequestHeader.Accept] = RequestHeaders.Json;
            this._client.Headers[HttpRequestHeader.ContentType] = RequestHeaders.UrlEncodedForm;

            this._client.UploadStringCompleted += new UploadStringCompletedEventHandler(_client_UploadStringCompleted);
            this._serviceLocation = serviceLocation;
            this._data = new List<IUrlSerializer>();
        }

        public void AddDataItem(IUrlSerializer dataItem)
        {
            this._data.Add(dataItem);
        }

        public void Send()
        {
            if (this._data.Count == 0)
            {
                throw new Exception("Data members are required to post form.");
            }

            StringBuilder sb = new StringBuilder();
            foreach (IUrlSerializer item in this._data)
            {
                sb.Append(item.SerializeToUrlString() + "&");
            }

            this._client.UploadStringAsync(this._serviceLocation, this._method, sb.ToString());
        }

        void _client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error == null && e.Result == PostResponse.Success)
            {
                if (this.PostComplete != null)
                {
                    this.PostComplete(this, EventArgs.Empty);
                }
            }
        }
    }
}